<?php

namespace App\Http\Controllers\Wechat;

use App\Common\Response;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class WxPayController extends Controller
{
    private $appid;
    private $mch_id;
    private $notify_url;
    private $key;

    public function __construct()
    {
        if (empty($config)){
            $config=config('wechat');
        }
        $this->appid = $config['appid'];
        $this->mch_id= $config['mch_id'];
        $this->key=$config['key'];
        $this->notify_url='http://echo.com/wechat/notify';
    }

    /**
     * Notes: 发起支付
     * User: aniu
     * Date: 2020/6/11
     * Time: 15:46
     * @return false|string
     */
    public function Pay(Request $request, Response $response)
    {
        $openid     = $request->post('openid');
        $user_id    = $request->post('user_id');
        $recharge_id = $request->post('recharge_id');
        $price = $request->post('price');
        $price  = isset($price) ? $price : 0;
//        $price = 0.01;
        $attach = "$user_id,$recharge_id, $price";
        $WeChatPay  = new OrderController($this->appid, $this->mch_id, $this->notify_url, $this->key, $openid);

        $params['body']         = '熊猫淘学-快批作业购买钻石'; //商品描述
        $params['out_trade_no'] = date('Ymd',time()).time().rand(10,99);; //自定义的订单号 time()."-".$openid
        $params['total_fee']    = $price * 100; //订单金额 只能为整数 单位为分
        $params['trade_type']   = 'JSAPI'; //交易类型 JSAPI | NATIVE | APP | WAP
        $params['attach'] = "$attach";
        $params['sign_type'] = 'MD5';
        $result = $WeChatPay->unifiedOrder($params);
        return $response->jsonResponse(2000, $result);
    }


    /**
     * Notes: 微信钻石回调
     * User: aniu
     * Date: 2020/6/11
     * Time: 16:16
     * @return mixed
     */
    public function notify()
    {
        $WeChatPay = new OrderController($this->appid, $this->mch_id, $this->notify_url, $this->key,'');
        //获取支付结果通知数据，并且将xml转换为array
        $data = $WeChatPay->getNotifyData();
        //保存微信服务器返回签名sign
        $data_sign = $data['sign'];
        // sign不参与签名算法
        unset($data['sign']);
        //生成签名
        $sign = $WeChatPay->MakeSign($data);
        /*  微信官方提醒：
         *  商户系统对于支付结果通知的内容一定要做【签名验证】,
         *  并校验返回的【订单金额是否与商户侧的订单金额】一致，
         *  防止数据泄漏导致出现“假通知”，造成资金损失。
         */
        // 判断签名是否正确  判断支付状态
        if (($sign === $data_sign) && ($data['return_code'] == 'SUCCESS') && ($data['result_code'] == 'SUCCESS')) {
            //获取服务器返回的数据
            $order_sn       = $data['out_trade_no'];          //订单单号
            $transaction_id = $data['transaction_id'];  //微信支付流水号
            $params = explode(',', $data['attach']);

            $price = $data['total_fee'] / 100;
            $userId = $params[0];
            $rechargeId = $params[1];
            $resultPrice = $params[2];
            if ($rechargeId){
                $this->curdOperation($userId, $rechargeId, $price, 1);
            }
            //通知微信接收通知成功
            $WeChatPay->replyNotify();
        }
        echo 'fail';
    }
}
